package com.alibaba.citrus.ots.forecast.repository.impl;

import com.alibaba.citrus.ots.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.ots.common.util.DateUtils;
import com.alibaba.citrus.ots.forecast.functions.forecastorder.constants.ForecastConstants;
import com.alibaba.citrus.ots.forecast.repository.DictValuesQueryRepository;
import com.alibaba.citrus.ots.forecast.repository.ForecastOrderQueryRepository;
import com.alibaba.citrus.ots.forecast.repository.impl.converter.ForecastOrderRepositoryConverter;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.service.ForecastSalesService;
import com.epoch.app.otsforecastsales.domian.forecastorder.dto.BatchQueryByIdsRequest;
import com.epoch.app.otsforecastsales.domian.forecastorder.dto.LoadForecastOrderList2Request;
import com.epoch.app.otsforecastsales.domian.forecastorder.dto.LoadForecastOrderRequest;
import com.epoch.app.otsforecastsales.domian.forecastorder.model.ForecastOrder;
import com.epoch.app.otsforecastsales.domian.forecastorder.service.ForecastOrderService;
import com.epoch.app.otsforecastsales.domian.forecastorderline.service.ForecastOrderLineService;
import com.epoch.app.otsforecastsales.enums.ForecastStatusEnum;
import com.epoch.app.otsforecastsales.model.dto.*;
import com.epoch.app.otsforecastsales.ofsforecastorderindex.model.OfsForecastOrderIndex;
import com.epoch.app.otsforecastsales.ofsforecastorderindex.service.OfsForecastOrderIndexService;
import com.epoch.app.otsforecastsales.sdo.ForecastOrderSDO;
import com.epoch.app.otsforecastsales.service.ApiService;
import com.epoch.app.otsforecastsales.service.ForecastOrderWriteService;
import com.epoch.app.otsplatformenhance.dictionaryquery.service.DictionaryQueryService;
import com.epoch.app.otsplatformenhance.model.dto.BatchQueryAddress2Request;
import com.epoch.app.otsplatformenhance.model.dto.BatchQueryAddress2Response;
import com.epoch.app.otsplatformenhance.model.dto.QueryDictionaryRequest;
import com.epoch.app.otsplatformenhance.sdo.CustomerAddressSDO;
import com.epoch.app.otsplatformenhance.sdo.DictionarySDO;
import com.epoch.app.otsplatformenhance.service.OtsPlatformEnhanceService;
import com.epoch.app.otspricecenter.api.creditquery.service.CreditQueryService;
import com.epoch.app.otspricecenter.model.dto.CreditReponse;
import com.epoch.app.otsunifiedinventory.model.dto.GetListWarehouseStockRequest;
import com.epoch.app.otsunifiedinventory.model.dto.WarehouseInventory;
import com.epoch.app.otsunifiedinventory.service.OtsUnifiedInventoryService;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.util.Pair;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

/**
 * @author: qiaojiange
 * @create: 2021/09/15
 * @Description 请描述类的业务用途
 */
@Service
public class ForecastOrderQueryRepositoryImpl implements ForecastOrderQueryRepository {
    private Log log = Log.getLogger(ForecastOrderQueryRepositoryImpl.class);
    //单据原因
    private static final String ORDER_REASON_TYPE = "orderReason";
    //运输方式
    private static final String SHIP_METHOD_TYPE = "shipMethod";
    @Resource
    ForecastOrderService forecastOrderService;
    @Resource
    ForecastSalesService forecastSalesService;

    @Resource
    ForecastOrderLineService forecastOrderLineService;
    @Resource
    private OtsPlatformEnhanceService otsPlatformEnhanceService;
    @Resource
    DictValuesQueryRepository dictValuesQueryRepository;
    @Resource
    ForecastOrderWriteService forecastOrderWriteService;
    @Resource
    private DictionaryQueryService dictionaryQueryService;
    @Resource
    OfsForecastOrderIndexService ofsForecastOrderIndexService;
    @Resource
    ApiService apiService;
    @Resource
    private CreditQueryService creditQueryService;

    @Resource
    private OtsUnifiedInventoryService otsUnifiedInventoryService;

    @Resource(name = "scItemsQueryTaskExecutor")
    private ThreadPoolTaskExecutor scItemsQueryTaskExecutor;

    // 库存查询循环查询较多， 参数重复度高， 增加30秒的缓存
    Cache<String, Double> inventoryCache = CacheBuilder.newBuilder()
            .maximumSize(3000) // 设置缓存的最大容量
            .expireAfterWrite(30, TimeUnit.SECONDS) // 设置缓存在写入一分钟后失效
            .concurrencyLevel(10) // 设置并发级别为10
            .recordStats() // 开启缓存统计
            .build();


    @Override
    @RepositoryInvoker(printLog = true)
    public ForecastOrderSDO load(String orderId) {
        LoadForecastOrderRequest loadRequest = new LoadForecastOrderRequest();
        loadRequest.setId(orderId);
        ForecastOrder forecastOrder = forecastOrderService.loadForecastOrder(loadRequest);
        ForecastOrderSDO forecastOrderSDO = convertForecastOrder(forecastOrder);
        return forecastOrderSDO;
    }

    public ForecastOrderSDO convertForecastOrder(ForecastOrder result) {

        Integer status = result.getStatus();
        String orderId = String.valueOf(result.getId());
        String bizCode = result.getBizCode();
        String businessCode = result.getBusinessCode();
        String outerOrderId = result.getOuterOrderId();
        String orderTag = result.getOrderTag();
        String customerName = result.getCustomerName();
        ForecastOrderSDO forecastOrderSDO = new ForecastOrderSDO();
        forecastOrderSDO.setId(orderId);
        forecastOrderSDO.setStatus(status);
        forecastOrderSDO.setBizCode(bizCode);
        forecastOrderSDO.setDepartmentCode(result.getDepartmentCode());
        forecastOrderSDO.setChannelCode(result.getChannelCode());
        forecastOrderSDO.setOrderTag(orderTag);
        forecastOrderSDO.setBusinessCode(businessCode);
        forecastOrderSDO.setOuterOrderId(outerOrderId);
        forecastOrderSDO.setCustomerName(customerName);
        forecastOrderSDO.setCustomerCode(result.getCustomerCode());
        forecastOrderSDO.setProductGroupCode(result.getProductGroupCode());
        forecastOrderSDO.setOrganizationCode(result.getOrganizationCode());
        forecastOrderSDO.setSaleChannelCode(result.getSaleChannelCode());
        forecastOrderSDO.setCustomerExpectTDate(result.getCustomerExpectTDate());
        forecastOrderSDO.setWareHouseCode(result.getWareHouseCode());
        forecastOrderSDO.setWareHouseName(result.getWareHouseName());
        forecastOrderSDO.setTransportModeName(result.getTransportModeName());
        forecastOrderSDO.setTransportModeCode(result.getTransportModeCode());
        forecastOrderSDO.setVaildBeginTime(result.getVaildBeginTime());
        forecastOrderSDO.setOrderType(result.getOrderType());
        forecastOrderSDO.setOrderBizId(result.getOrderBizId());
        forecastOrderSDO.setSalesmanCode(result.getSalesmanId());
        forecastOrderSDO.setSalesmanName(result.getSalesmanName());
        forecastOrderSDO.setReceiveAddressCode(result.getReceiveAddressCode());
        return forecastOrderSDO;
    }
    @Override
    public ForecastOrderSDO queyrDetail(String orderId,boolean isQueryCredit) {
        LoadForecastOrderRequest mainLoadRequest = new LoadForecastOrderRequest();
        mainLoadRequest.setId(orderId);
        ForecastOrder forecastOrder = forecastOrderService.loadForecastOrder(mainLoadRequest);
        ForecastOrderSDO forecastOrderSDOResult = new ForecastOrderSDO();
//        BeanUtils.copyProperties(forecastOrder,forecastOrderSDOResult);
        forecastOrderSDOResult.setId(orderId);

        Map features = StringUtils.isNotBlank(forecastOrder.getFeatures())? JSONObject.parseObject(forecastOrder.getFeatures(),Map.class):new HashMap();
        forecastOrderSDOResult.setAppCreate(Boolean.FALSE);
        if (MapUtils.isNotEmpty(features)) {
            if (Objects.nonNull(features.get(ForecastConstants.OS))&&StringUtils.isNotBlank(String.valueOf(features.get(ForecastConstants.OS)))){
                String os = String.valueOf(features.get(ForecastConstants.OS));
                if ("app".equalsIgnoreCase(os)){
                    forecastOrderSDOResult.setAppCreate(Boolean.TRUE);
                }
            }
        }

        forecastOrderSDOResult.setId(forecastOrder.getId().toString());
        forecastOrderSDOResult.setBizCode(forecastOrder.getBizCode());
        forecastOrderSDOResult.setBusinessCode(forecastOrder.getBusinessCode());
        forecastOrderSDOResult.setOuterOrderId(forecastOrder.getOuterOrderId());
        forecastOrderSDOResult.setOrderTag(forecastOrder.getOrderTag());
        forecastOrderSDOResult.setCustomerCode(forecastOrder.getCustomerCode());
        Map<String, String> enumMap = dictValuesQueryRepository.queryValues("forecastTag");
        String lable = enumMap.get(forecastOrder.getOrderType());
        forecastOrderSDOResult.setOrderValue(lable);
        Map<String, String> shipMethod = dictValuesQueryRepository.queryValues("shipMethod");
        String transportMode = shipMethod.get(forecastOrder.getTransportModeCode());
        forecastOrderSDOResult.setTransportModeName(transportMode);
        forecastOrderSDOResult.setModifierName(forecastOrder.getModifierName());
        forecastOrderSDOResult.setOrderType(forecastOrder.getOrderType());
        forecastOrderSDOResult.setCustomerName(forecastOrder.getCustomerName());
        forecastOrderSDOResult.setOrganizationCode(forecastOrder.getOrganizationCode());
        forecastOrderSDOResult.setOrganizationName(forecastOrder.getOrganizationName());
        forecastOrderSDOResult.setDepartmentCode(forecastOrder.getDepartmentCode());
        forecastOrderSDOResult.setDepartmentName(forecastOrder.getDepartmentName());
        forecastOrderSDOResult.setProductGroupCode(forecastOrder.getProductGroupCode());
        forecastOrderSDOResult.setProductGroupName(forecastOrder.getProductGroupName());
        forecastOrderSDOResult.setSaleChannelCode(forecastOrder.getSaleChannelCode());
        forecastOrderSDOResult.setSaleChannelName(forecastOrder.getSaleChannelName());
        forecastOrderSDOResult.setChannelCode(forecastOrder.getChannelCode());
        forecastOrderSDOResult.setChannelName(forecastOrder.getChannelName());
        forecastOrderSDOResult.setShipAddressCode(forecastOrder.getShipAddressCode());
        forecastOrderSDOResult.setShipAddressInfo(forecastOrder.getShipAddressInfo());
        forecastOrderSDOResult.setReceiveAddressCode(forecastOrder.getReceiveAddressCode());
        forecastOrderSDOResult.setReceiveDetailAddress(forecastOrder.getReceiveDetailAddress());
        forecastOrderSDOResult.setContact(forecastOrder.getContact());
        forecastOrderSDOResult.setContactPhone(forecastOrder.getContactPhone());
        forecastOrderSDOResult.setTransportModeCode(forecastOrder.getTransportModeCode());
        forecastOrderSDOResult.setTransportModeName(forecastOrder.getTransportModeName());
        forecastOrderSDOResult.setCreateReason(forecastOrder.getCreateReason());
        forecastOrderSDOResult.setRemark(forecastOrder.getRemark());
        forecastOrderSDOResult.setWareHouseCode(forecastOrder.getWareHouseCode());
        forecastOrderSDOResult.setWareHouseName(forecastOrder.getWareHouseName());
        forecastOrderSDOResult.setOrderTotalFee(forecastOrder.getOrderTotalFee());
        forecastOrderSDOResult.setTotalActivityFee(forecastOrder.getTotalActivityFee());
        forecastOrderSDOResult.setTotalReplyAmount(forecastOrder.getTotalReplyAmount());
        forecastOrderSDOResult.setTotalPredictAmount(forecastOrder.getTotalPredictAmount());
        //实时查询信贷

        com.epoch.app.otspricecenter.model.dto.QueryCreditRequest creditRequest = new com.epoch.app.otspricecenter.model.dto.QueryCreditRequest();
        creditRequest.setChannelCode(forecastOrder.getChannelCode());
        creditRequest.setOrganizationCode(forecastOrder.getOrganizationCode());
        creditRequest.setItemGroupCode(forecastOrder.getProductGroupCode());
        creditRequest.setCustomerCode(forecastOrder.getCustomerCode());
//        creditRequest.setClientCode();
        forecastOrderSDOResult.setCreditBalance(forecastOrder.getCreditBalance());
        CompletableFuture<String> creditFuture=null;
        if(isQueryCredit){
            creditFuture= CompletableFuture.supplyAsync(() -> {
                String balance = null;
                Result<CreditReponse> creditReponseResult = creditQueryService.queryCreditBalance(creditRequest);
                if (creditReponseResult.isSuccess()) {
                    balance = creditReponseResult.getResult().getBalance();
                } else {
                    log.error("查询信贷余额失败：" + forecastOrder.getOrderBizId());
                }
                return balance;
            }, scItemsQueryTaskExecutor);
        }

        forecastOrderSDOResult.setCustomerReferenceNo(forecastOrder.getCustomerReferenceNo());
        forecastOrderSDOResult.setCustomerExpectTDate(forecastOrder.getCustomerExpectTDate());
        forecastOrderSDOResult.setReplyTime(forecastOrder.getReplyTime());
        forecastOrderSDOResult.setReplyStatus(forecastOrder.getReplyStatus());
        forecastOrderSDOResult.setRefuseStatus(forecastOrder.getRefuseStatus());
        forecastOrderSDOResult.setRefuseTime(forecastOrder.getRefuseTime());
        forecastOrderSDOResult.setStatus(forecastOrder.getStatus());
        forecastOrderSDOResult.setConfirmTime(forecastOrder.getConfirmTime());
        forecastOrderSDOResult.setConfirmStatus(forecastOrder.getConfirmStatus());
        forecastOrderSDOResult.setDealStatus(forecastOrder.getDealStatus());
        forecastOrderSDOResult.setFinishedTime(forecastOrder.getFinishedTime());
        forecastOrderSDOResult.setIdemId(forecastOrder.getIdemId());
        forecastOrderSDOResult.setVaildBeginTime(forecastOrder.getVaildBeginTime());
        forecastOrderSDOResult.setValidEndTime(forecastOrder.getValidEndTime());
        forecastOrderSDOResult.setGmtCreate(forecastOrder.getGmtCreate());
        forecastOrderSDOResult.setGmtModified(forecastOrder.getGmtModified());
        forecastOrderSDOResult.setCreatorId(forecastOrder.getCreatorId());
        forecastOrderSDOResult.setCreatorName(forecastOrder.getCreatorName());
        forecastOrderSDOResult.setOrderBizId(forecastOrder.getOrderBizId());
        forecastOrderSDOResult.setBisUnitCode(forecastOrder.getBisUnitCode());
        forecastOrderSDOResult.setAreaCode(forecastOrder.getAreaCode());
        forecastOrderSDOResult.setSalesmanCode(forecastOrder.getSalesmanId());
        forecastOrderSDOResult.setSalesmanName(forecastOrder.getSalesmanName());
        forecastOrderSDOResult.setSyncVersion(forecastOrder.getSyncVersion());
        forecastOrderSDOResult.setAreaCode(forecastOrder.getAreaCode());
        forecastOrderSDOResult.setBisUnitCode(forecastOrder.getBisUnitCode());
        forecastOrderSDOResult.setSalesmanCode(forecastOrder.getSalesmanId());
        forecastOrderSDOResult.setSalesmanName(forecastOrder.getSalesmanName());
        QueryDictionaryRequest queryDictionaryRequest = new QueryDictionaryRequest();
        //获取单据原因的名称
        if (StringUtils.isNotBlank(forecastOrder.getCreateReason())) {
            queryDictionaryRequest.setDictCode(ORDER_REASON_TYPE);
            Result<DictionarySDO> dictionarySDOResult = dictionaryQueryService.querySingle(queryDictionaryRequest);
            dictionarySDOResult.getResult().getDictValueList().stream().forEach(x -> {
                if (x.getValueData().equals(forecastOrder.getCreateReason())) {
                    forecastOrderSDOResult.setCreateReasonName(x.getValueName());
                }
            });
        }
        //获取配送方式名称
        if (StringUtils.isNotBlank(forecastOrder.getTransportModeCode())) {
            queryDictionaryRequest.setDictCode(SHIP_METHOD_TYPE);
            Result<DictionarySDO> dictionarySDOResult = dictionaryQueryService.querySingle(queryDictionaryRequest);
            dictionarySDOResult.getResult().getDictValueList().stream().forEach(x -> {
                if (x.getValueData().equals(forecastOrder.getTransportModeCode())) {
                    forecastOrderSDOResult.setTransportModeName(x.getValueName());
                }
            });
        }

        //获取收货地址
        BatchQueryAddress2Request batchQueryAddress2Request = new BatchQueryAddress2Request();
        batchQueryAddress2Request.setAddressCodes(Lists.newArrayList(forecastOrder.getReceiveAddressCode()));
        BatchQueryAddress2Response batchQueryAddress2Response = otsPlatformEnhanceService.batchQueryAddress2(batchQueryAddress2Request);
        if (Objects.nonNull(batchQueryAddress2Response) && CollectionUtils.isNotEmpty(batchQueryAddress2Response.getResult())) {
            CustomerAddressSDO customerAddressSDO = batchQueryAddress2Response.getResult().stream().findFirst().get();
            forecastOrderSDOResult.setAddressName(customerAddressSDO.getAddress());
        }
        if(isQueryCredit&&Objects.nonNull(creditFuture)){
            String creditBalance = null;
            try {
                creditBalance = creditFuture.get(2, TimeUnit.SECONDS);
            } catch (Exception e) {
                log.error("查询信贷余额失败：" + forecastOrder.getOrderBizId(), e);
            }
            forecastOrderSDOResult.setCreditBalance(creditBalance);
        }




        return forecastOrderSDOResult;
    }

    @Override
    public ForecastOrderSDO queyrDetail(String orderId) {
        return queyrDetail(orderId,false);
    }

    @Override
    public List<ForecastOrderSDO> batchQueryForecastOrder(List<String> ids) {
        BatchQueryByIdsRequest batchQueryByIdsRequest = new BatchQueryByIdsRequest();
        batchQueryByIdsRequest.setIds(ids);
        Result<List<ForecastOrder>> listResult = forecastOrderService.batchQueryByIds(batchQueryByIdsRequest);
        List<ForecastOrder> result = listResult.getResult();
        ArrayList<ForecastOrderSDO> forecastOrderSDOArrayList = new ArrayList<>();
        for (ForecastOrder forecastOrder : result) {
            ForecastOrderSDO forecastOrderSDO = new ForecastOrderSDO();
            BeanUtils.copyProperties(forecastOrder, forecastOrderSDO);
            forecastOrderSDO.setId(String.valueOf(forecastOrder.getId()));
            forecastOrderSDOArrayList.add(forecastOrderSDO);
        }
        return forecastOrderSDOArrayList;
    }

    /**
     * 分页查询预售订单列表
     */
    @Override
    public PageResult<List<ForecastOrderSDO>> pageQuery(ForecastOrderSDO forecastOrderSDO) {
        LoadForecastOrderList2Request request = ForecastOrderRepositoryConverter.toForecastOrderLoadListRequest(forecastOrderSDO);
        if (!ObjectUtils.allNotNull(request.getStart())) {
            request.setStart(0);
        }
        if (ObjectUtils.allNotNull(request.getLimit())) {
            request.setLimit(20);
        }
        Result<List<ForecastOrder>> listResult = forecastOrderService.loadForecastOrderList2(request);
        //  Result<List<ForecastOrder>> listResult = null;
        Map<String, String> enumMap = dictValuesQueryRepository.queryValues("forecastTag");
        List<ForecastOrderSDO> collect = Nullable.stream(listResult.getResult()).map(forecastOrder -> ForecastOrderRepositoryConverter.toForecastOrderSDO(forecastOrder, enumMap)).collect(Collectors.toList());
        return PageResult.of(collect, listResult.getTotal());

    }

    @Override
    public QueryCreditResponse queryCredit(List data) {
        QueryCreditResponse queryCreditResponse = new QueryCreditResponse();
        QueryCreditRequest queryCreditRequest = new QueryCreditRequest();
        queryCreditRequest.setData(data);
        QueryCreditResponse queryCreditResponse1 = apiService.queryCredit(queryCreditRequest);
        return queryCreditResponse;
    }


    //TODO 库存数要么bigDecimal 要么用Long/Int,涉及到精度计算勿使用Double/Float
    @RepositoryInvoker(printLog = true)
    @Override
    public Double queryInventory(QueryAvailableInventoryRequest queryAvailableInventoryRequest) {
        // 很多地方都会用到查询库存的， 增加本地缓存优化性能
        String warehouseAreaId = Optional.ofNullable(queryAvailableInventoryRequest.getWarehouseAreaId()).orElse("");
        String goodsId = Optional.ofNullable(queryAvailableInventoryRequest.getGoodsId()).orElse("");
        String type = Optional.ofNullable(queryAvailableInventoryRequest.getType()).orElse("");
        String warehouseId = Optional.ofNullable(queryAvailableInventoryRequest.getWarehouseId()).orElse("");
        String cacheKey = String.format("%s-%s-%s-%s", warehouseAreaId, goodsId, type, warehouseId);
        Double inventory = inventoryCache.getIfPresent(cacheKey);
        if (inventory != null && inventory > 0) {
            return inventory;
        }

        QueryInventoryRequest queryInventoryRequest = new QueryInventoryRequest();
        BeanUtils.copyProperties(queryAvailableInventoryRequest, queryInventoryRequest);
        QueryInventoryResponse queryInventoryResponse = forecastOrderWriteService.queryInventory(queryInventoryRequest);
        Double availableQuantity = 0D;
        if (Objects.nonNull(queryInventoryResponse) && Objects.nonNull(queryInventoryResponse.getResult())) {
            Map result = (Map) queryInventoryResponse.getResult();
            if (ObjectUtils.allNotNull(result.get("availableQuantityFormat"))) {
                availableQuantity = Double.parseDouble((String) result.get("availableQuantityFormat"));
                if (availableQuantity != null) {
                    inventoryCache.put(cacheKey, availableQuantity);
                }
            }
        }

        return availableQuantity;
    }

    @Override
    public PageResult<List<ForecastOrderSDO>> pageQueryByEs(PageQueryForecastLineRequest pageQueryForecastLineRequest) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, 1);
        Date tomorrowFirstTime = DateUtils.getFirstTime(calendar.getTime());
        SearchForecastOrderRequest searchForecastOrderRequest = new SearchForecastOrderRequest();
        Result<List<OfsForecastOrderIndex>> listResult = ofsForecastOrderIndexService.queryForecastOrderList(searchForecastOrderRequest);
        Map<String, String> enumMap = dictValuesQueryRepository.queryValues("forecastTag");
        List<ForecastOrderSDO> collect = Nullable.stream(listResult.getResult()).map(it -> ForecastOrderRepositoryConverter.indexToQueryForecastSDO(it, enumMap, tomorrowFirstTime)).collect(Collectors.toList());
        PageResult<List<ForecastOrderSDO>> of = PageResult.of(collect, listResult.getTotal());
        return of;
    }

    @Override
    public Result<List<ForecastOrderSDO>> pageQueryByEs(SearchForecastOrderRequest searchForecastOrderRequest) {

        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, 1);
        Date tomorrowFirstTime = DateUtils.getFirstTime(calendar.getTime());

        // 查询待回复 要查询 1.待回复状态 和 2.生效时间是当天及以前的
        if (CollectionUtils.isNotEmpty(searchForecastOrderRequest.getMainStatusList()) && searchForecastOrderRequest.getMainStatusList().contains(ForecastStatusEnum.WAITING_FOR_REPLY.getNumValue())) {
            searchForecastOrderRequest.setValidEndDate(DateUtils.getLatestTime(new Date()));
        }
        // 查询 未生效的  查询  1.待回复状态  2.生效时间为 当天以后的，
        if (CollectionUtils.isNotEmpty(searchForecastOrderRequest.getMainStatusList()) && searchForecastOrderRequest.getMainStatusList().contains(ForecastStatusEnum.NOTACTIVE.getNumValue())) {
            List<Integer> mainStatusList = searchForecastOrderRequest.getMainStatusList();
            mainStatusList.add(ForecastStatusEnum.WAITING_FOR_REPLY.getNumValue());
            searchForecastOrderRequest.setMainStatusList(mainStatusList);
            searchForecastOrderRequest.setValidStartDate(tomorrowFirstTime);
        }
        //小程序 特判，如果有特判值传入，只使用传入的状态集合
        if (CollectionUtils.isNotEmpty(searchForecastOrderRequest.getMainStatusList()) && searchForecastOrderRequest.getMainStatusList().contains(ForecastStatusEnum.MINI_SPEC_JUDGE.getNumValue())) {
            searchForecastOrderRequest.setMainStatusList(searchForecastOrderRequest.getMainStatusList());
            searchForecastOrderRequest.setValidEndDate(null);
            searchForecastOrderRequest.setValidStartDate(null);
        }



        Result<List<OfsForecastOrderIndex>> listResult = ofsForecastOrderIndexService.queryForecastOrderList(searchForecastOrderRequest);
        Map<String, String> enumMap = dictValuesQueryRepository.queryValues("forecastTag");
        List<ForecastOrderSDO> collect = Nullable.stream(listResult.getResult()).map(it -> ForecastOrderRepositoryConverter.indexToQueryForecastSDO(it, enumMap, tomorrowFirstTime)).collect(Collectors.toList());
        return Result.listSuccess(collect, listResult.getTotal());
    }

    @Override
    public Result<Long> countForecastOrder(SearchForecastOrderRequest searchForecastOrderRequest) {

        return ofsForecastOrderIndexService.queryForecastOrderListForCount(searchForecastOrderRequest);

    }

    @RepositoryInvoker
    @Override
    public List<WarehouseInventory> getListWarehouseStock(GetListWarehouseStockRequest getListWarehouseStockRequest) {
        Result<List<WarehouseInventory>> warehouseStockList = otsUnifiedInventoryService.getListWarehouseStock(getListWarehouseStockRequest);

        if (warehouseStockList != null && warehouseStockList.isSuccess()) {
            return warehouseStockList.getResult();
        }

        return null;
    }


}